/**
 * created by 文阿花, 2021/6/21
 * Copyright (c) 2021, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.light.mytext.mycustomview.pic

import android.content.Context
import android.graphics.*
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.MotionEvent
import com.light.mytext.R
import com.light.mytext.utiles.ToolUtils
import com.light.mytext.views.pics.SingleTouchView

/**
 * 描 述：
 * 作 者：文阿花  2021-06-21 15:36
 * 修改描述：
 * 修 改 人：
 * 修改版本：
 */
class ImageviewTouchView : androidx.appcompat.widget.AppCompatImageView {
    /*移动旋转工具类*/
    var matrix_operate: Matrix? = Matrix()

    //当前位置
    var matrix_current: Matrix? = Matrix()
    private val startPoint = PointF()

    //拖动标记
    private val DRAG = 1 //拖动
    private val ZOOM = 2 //放大
    var mode = 0//默认状态

    /**
     * 一些默认的常量
     */
    val DEFAULT_FRAME_PADDING = 8
    val DEFAULT_FRAME_WIDTH = 2
    val DEFAULT_FRAME_COLOR = Color.WHITE
    val DEFAULT_SCALE = 1.5f
    val DEFAULT_DEGREE = 0f
    val DEFAULT_CONTROL_LOCATION = SingleTouchView.RIGHT_TOP
    val DEFAULT_EDITABLE = true
    val DEFAULT_OTHER_DRAWABLE_WIDTH = 50
    val DEFAULT_OTHER_DRAWABLE_HEIGHT = 50

    /**
     * 外边框与图片之间的间距, 单位是dip
     */
    private var framePadding = DEFAULT_FRAME_PADDING

    /**
     * 外边框颜色
     */
    private var frameColor = DEFAULT_FRAME_COLOR

    /**
     * 外边框线条粗细, 单位是 dip
     */
    private var frameWidth = DEFAULT_FRAME_WIDTH

    /**
     * 是否处于可以缩放，平移，旋转状态
     */
    private var isEditable = DEFAULT_EDITABLE

    /**
     * 用于旋转缩放的Bitmap
     */
    private var mBitmap: Bitmap? = null

    /**
     * 图片的旋转角度
     */
    private var mDegree = SingleTouchView.DEFAULT_DEGREE

    /**
     * 图片的缩放比例
     */
    private var mScale = SingleTouchView.DEFAULT_SCALE

    /**
     * 用于缩放，旋转的图标
     */
    private var controlDrawable: Drawable? = null

    /**
     * 控制图标所在的位置（比如左上，右上，左下，右下）
     */
    private var controlLocation = SingleTouchView.DEFAULT_CONTROL_LOCATION
    private var metrics: DisplayMetrics? = null

    /**
     * 图片的宽高
     */
    private var mViewWidth: Int = 0
    private var mViewHeight: Int = 0

    constructor(context: Context?) : super(context!!) {
        initData()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs) {
        initData()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context!!,
        attrs,
        defStyleAttr
    ) {
        obtainStyledAttributes(attrs)
        initData()

    }

    /**
     * 获取自定义性质
     */
    fun obtainStyledAttributes(attrs: AttributeSet?) {
        metrics = context.resources.displayMetrics
        framePadding = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            SingleTouchView.DEFAULT_FRAME_PADDING.toFloat(),
            metrics
        )
            .toInt()
        frameWidth = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            SingleTouchView.DEFAULT_FRAME_WIDTH.toFloat(),
            metrics
        )
            .toInt()

        var mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.SingleTouchView)
        var mDrawable = mTypedArray.getDrawable(R.styleable.SingleTouchView_src)
        mBitmap = ToolUtils.drawable2Bitmap(mDrawable)

        framePadding = mTypedArray.getDimensionPixelSize(
            R.styleable.SingleTouchView_framePadding,
            framePadding
        )
        frameWidth =
            mTypedArray.getDimensionPixelSize(R.styleable.SingleTouchView_frameWidth, frameWidth)
        frameColor = mTypedArray.getColor(
            R.styleable.SingleTouchView_frameColor1,
            SingleTouchView.DEFAULT_FRAME_COLOR
        )
        mScale =
            mTypedArray.getFloat(R.styleable.SingleTouchView_scale, SingleTouchView.DEFAULT_SCALE)
        mDegree =
            mTypedArray.getFloat(R.styleable.SingleTouchView_degree, SingleTouchView.DEFAULT_DEGREE)
        controlDrawable = mTypedArray.getDrawable(R.styleable.SingleTouchView_controlDrawable)
        controlLocation = mTypedArray.getInt(
            R.styleable.SingleTouchView_controlLocation,
            SingleTouchView.DEFAULT_CONTROL_LOCATION
        )
        isEditable = mTypedArray.getBoolean(
            R.styleable.SingleTouchView_editable,
            SingleTouchView.DEFAULT_EDITABLE
        )

        mTypedArray.recycle()
    }

    fun initData() {
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (mBitmap == null) {
            return
        }
        canvas.drawBitmap(mBitmap!!, matrix, null)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event!!.action) {
            //单指触碰
            MotionEvent.ACTION_DOWN -> {
                mode = DRAG
                //记录img当前位置
                matrix_current!!.set(this.imageMatrix)
                startPoint.set(event.x, event.y)
            }
            MotionEvent.ACTION_MOVE -> {
                if (mode == DRAG) {//拖动
                    //移动距离
                    var distance_x = event.x - startPoint.x
                    var distance_y = event.y - startPoint.y
                    //matrix_operate在matrix_current基础上移动
                    matrix_operate!!.set(matrix_current)
                    //移动
                    matrix_operate!!.postTranslate(distance_x, distance_y)
                }

            }
            //有手指抬起，但屏幕上依旧有触点(屏幕上一个触点即拖动)
            MotionEvent.ACTION_POINTER_UP -> {
                mode = DRAG
            }
            //双指触碰
            MotionEvent.ACTION_POINTER_DOWN -> {
                mode = ZOOM
            }
            MotionEvent.ACTION_UP -> {
                mode = 0

            }


        }
        scaleType = ScaleType.MATRIX
        imageMatrix = matrix_operate
        return true
    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        /*setMeasuredDimension(
            MiscUtil.measure(widthMeasureSpec, width),
            MiscUtil.measure(heightMeasureSpec, height)
        )*/
    }

}